package sslf.com.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import sslf.com.domain.User;
import sslf.com.service.TestService;

@Controller
public class TestController {

	@Autowired
	private TestService testService;

	@RequestMapping("test.html")
	public String test(String aa) {
		// System.out.println(aa);

		User u = this.testService.select();
		System.out.println(u.getUserId());
		return ".main.index";
	}

	@RequestMapping("testTransactional.html")
	public String testTransactional() {
		try {
			this.testService.testTransactional();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ".main.index";
	}

	@RequestMapping("jumpUploadPage.html")
	public String jumpUploadPage() {
		return ".main.up";
	}
	
	@RequestMapping(value = "testUpload.html", method = RequestMethod.POST)
	public String testUpload(HttpServletRequest request) throws IllegalStateException, IOException {
		// 设置上下文
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

		// 检查form是否带有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest servletRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = servletRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = servletRequest.getFile(iter.next());
				if (file != null) {
					String fileName = "demoUpload" + file.getOriginalFilename();
					String path = "D:/" + fileName;

					File localFile = new File(path);
					file.transferTo(localFile);
				}
			}
		}
		return "dataSuccess";
	}
	
	
	
	@RequestMapping("jumpUploadPageify.html")
	public String jumifyPage() {
		return ".main.uploadify";
	}
	
	@RequestMapping(value = "testUploadify.html", method = RequestMethod.POST)
	public void testUploadify(HttpServletRequest request) throws IllegalStateException, IOException {
		System.out.println("ify");
	}
}
